package cz.mpelant.msoe.mealchecker;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;

import cz.mpelant.msoe.mealchecker.downloader.Downloader;

public class BaseActivity extends SherlockActivity {
	protected final int MIN_TIME_BETWEEN_DOWNLOADS = 100 * 60 * 5;
	protected Downloader downloader;
	protected boolean isRefreshing;
	protected boolean isActivityActive;
	private BroadcastReceiver downloaderStatusReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			switch (intent.getIntExtra(Downloader.EXTRA_STATUS, -1)) {
			case Downloader.STATUS_STARTED:
				setRefreshing(true);
				break;
			case Downloader.STATUS_FINISHED:
				if (!downloader.isRunning())
					setRefreshing(false);
				downloadFinished();
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		getSupportActionBar().setHomeButtonEnabled(true);
		checkLogin();
		
		downloader = Downloader.getInstance(this);
	}

	protected void checkLogin() {
		if (!LoginActivity.isLoginInfo(this)) {
			startActivity(new Intent(this, LoginActivity.class));
		}
	}

	protected File getInternalFile(String fname) {
		return new File(getFilesDir(), fname);
	}

	protected File getCacheFile(String fname) {
		return new File(getCacheDir(), fname);
	}

	protected void copyFile(InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[1024];
		int read;
		while ((read = in.read(buffer)) != -1) {
			out.write(buffer, 0, read);
		}
	}

	protected void setRefreshing(boolean isRefreshing) {
		setSupportProgressBarIndeterminateVisibility(isRefreshing);
		this.isRefreshing = isRefreshing;
		invalidateOptionsMenu();
	}

	@Override
	protected void onPause() {
		try {
			unregisterReceiver(downloaderStatusReceiver);
		} catch (Exception e) {
		}

		isActivityActive = false;
		super.onPause();
	}

	@Override
	protected void onResume() {
		if (!LoginActivity.isLoginInfo(this)) {
			super.onResume();
			finish();
			return;
		} else {
			if (downloader.isRunning()) {
				setRefreshing(true);
			} else {
				setRefreshing(false);
			}
			registerReceiver(downloaderStatusReceiver, new IntentFilter(downloader.getActionDownloadStatus()));
			isActivityActive = true;

			super.onResume();
		}
	}

	protected void downloadFinished() {

	}

	protected static String readFileAsString(File f) throws java.io.IOException {
		StringBuffer fileData = new StringBuffer(1000);
		BufferedReader reader = new BufferedReader(new FileReader(f));
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
			buf = new char[1024];
		}
		reader.close();
		return fileData.toString();
	}

	protected void storeFileFromCache(String fname) {
		Log.i("meal", "storing file");
		File cache = getCacheFile(fname);
		File stored = getInternalFile(fname);
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			in = new FileInputStream(cache);
			out = new FileOutputStream(stored);
			copyFile(in, out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent intent = new Intent(this, MainActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem menuItem;
		menuItem = menu.add(R.string.logout);
		menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
		menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				Intent i = new Intent(BaseActivity.this, LoginActivity.class);
				i.putExtra(LoginActivity.INTENT_LOGOUT, true);
				i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				deleteFiles();
				startActivity(i);
				finish();
				return true;
			}
		});
		if (!isRefreshing) {
			menuItem = menu.add(Menu.NONE, 1, Menu.NONE, R.string.refresh);
			menuItem.setIcon(R.drawable.ic_refresh);
			menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
				@Override
				public boolean onMenuItemClick(MenuItem item) {
					refresh();
					return true;
				}
			});
		}
		return super.onCreateOptionsMenu(menu);
	}

	protected void refresh() {

	}

	protected void deleteFiles() {
		File[] files = getFilesDir().listFiles();

		if (files != null) {
			for (File file : files)
				file.delete();
		}
		files = getCacheDir().listFiles();

		if (files != null) {
			for (File file : files)
				file.delete();
		}
		downloader.clearCookies();

	}

}
